package com.dpl.yyrj.ui.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.dpl.widget.layout.WrapRecyclerView;
import com.dpl.widget.view.SwitchButton;
import com.dpl.yyrj.R;
import com.dpl.yyrj.aop.SingleClick;
import com.dpl.yyrj.app.TitleBarFragment;
import com.dpl.yyrj.ui.activity.HomeActivity;
import com.dpl.yyrj.ui.activity.ImageSelectActivity;
import com.dpl.yyrj.ui.adapter.AddDataAdapter;
import com.dpl.yyrj.ui.data.DataOfKey;
import com.dpl.yyrj.ui.data.ItemEdit;
import com.dpl.yyrj.utils.BitmapUtils;
import com.dpl.yyrj.utils.DateUtil;
import com.dpl.yyrj.utils.DensityUtils;
import com.dpl.yyrj.utils.JsonUtil;
import com.dpl.yyrj.utils.LogUtil;
import com.dpl.yyrj.utils.MMKVUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.hjq.bar.TitleBar;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * author : Android dpl
 * -------------
 * time   : 2018/10/18
 * desc   : 发现 Fragment
 */
public final class AddRecordFragment extends TitleBarFragment<HomeActivity>
        implements SwitchButton.OnCheckedChangeListener {


    private TextView record_weiyang;
    private ConstraintLayout linear_weiyang;
    private TextView record_shengli;
    private LinearLayoutCompat linear_shenli;
    private TextView record_weiliangyuansu;
    private LinearLayoutCompat linear_weiliangyuansu;
    private TextView record_remark;
    private LinearLayoutCompat linear_remark;
    private TextView record_pic;
    private LinearLayoutCompat linear_pick_pic;
    private LinearLayoutCompat linear_content_add_data;

    private ImageView img_today;
    private TitleBar tv_title;
    private WrapRecyclerView rv_weiyang_list;
    private WrapRecyclerView rv_shengli_list;
    private WrapRecyclerView rv_weiliangyuansu_list;

    private AddDataAdapter weiyangAdapter;
    private AddDataAdapter shengliAdapter;
    private AddDataAdapter weiliangyuansuAdapter;

    private List<ItemEdit> weiyangAdapterData;
    private List<ItemEdit> shenliAdapterData;
    private List<ItemEdit> weiliangyuansuAdapterData;

    private final static int WEIYANGTAG = 0;
    private final static int SHENLI = 1;
    private final static int WEILIANGYUANSU = 2;

    private final static String TAG = "AddRecordFragment";

    private Long lastRefreshTime = 0L;

    private String imgPath = "";
    private String remark = "";

    private Date date;

    private String day = "";
    private boolean isInited = false;
    private EditText record_data_words;

    public static AddRecordFragment newInstance(Date date) {
        Bundle bundle = new Bundle();
        bundle.putLong(DataOfKey.KEY_MMKV_DAY, date.getTime());
        AddRecordFragment fragment = new AddRecordFragment();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_add_record;
    }

    @Override
    protected void initView() {

        record_weiyang = findViewById(R.id.record_weiyang);
        linear_weiyang = findViewById(R.id.linear_weiyang);
        record_shengli = findViewById(R.id.record_shengli);
        linear_shenli = findViewById(R.id.linear_shenli);
        record_weiliangyuansu = findViewById(R.id.record_weiliangyuansu);
        linear_weiliangyuansu = findViewById(R.id.linear_weiliangyuansu);
        record_remark = findViewById(R.id.record_remark);
        linear_remark = findViewById(R.id.linear_remark);
        record_pic = findViewById(R.id.record_pic);
        linear_pick_pic = findViewById(R.id.linear_pick_pic);
        linear_content_add_data = findViewById(R.id.linear_content_add_data);

        img_today = findViewById(R.id.img_today);
        img_today.setOnClickListener(this);

        tv_title = findViewById(R.id.tv_title);

        rv_weiyang_list = findViewById(R.id.rv_weiyang_list);
        rv_shengli_list = findViewById(R.id.rv_shengli_list);
        rv_weiliangyuansu_list = findViewById(R.id.rv_weiliangyuansu_list);
        record_data_words = findViewById(R.id.record_data_words);
    }

    @Override
    protected void initData() {

        date = new Date(getBundle().getLong(DataOfKey.KEY_MMKV_DAY));
        day = DateUtil.formatDay(date);
        tv_title.setTitle(getToday());

        weiyangAdapter = new AddDataAdapter(getActivity());
        weiyangAdapterData = new ArrayList<>();
        weiyangAdapterData.add(new ItemEdit("添加记录", "时间", DataOfKey.KEY_WEIYANG));


        shengliAdapter = new AddDataAdapter(getActivity());
        shenliAdapterData = new ArrayList<>();
        shenliAdapterData.add(new ItemEdit("添加记录", "时间", DataOfKey.KEY_SHENGLI));


        weiliangyuansuAdapter = new AddDataAdapter(getActivity());
        weiliangyuansuAdapterData = new ArrayList<>();
        weiliangyuansuAdapterData.add(new ItemEdit("添加记录", "时间", DataOfKey.KEY_WEILIANGYUANSU));


        weiyangAdapter.setData(weiyangAdapterData);
        rv_weiyang_list.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv_weiyang_list.setAdapter(weiyangAdapter);
        TextView weiyangFooter = rv_weiyang_list.addFooterView(R.layout.item_add);
        weiyangFooter.setOnClickListener(v ->
                        notifyData(WEIYANGTAG)
                                        );

        shengliAdapter.setData(shenliAdapterData);
        rv_shengli_list.setAdapter(shengliAdapter);
        TextView shengliFooter = rv_shengli_list.addFooterView(R.layout.item_add);
        shengliFooter.setOnClickListener(v ->
                        notifyData(SHENLI)
                                        );

        weiliangyuansuAdapter.setData(weiliangyuansuAdapterData);
        rv_weiliangyuansu_list.setAdapter(weiliangyuansuAdapter);
        TextView weiliangyuansuFooter = rv_weiliangyuansu_list.addFooterView(R.layout.item_add);
        weiliangyuansuFooter.setOnClickListener(v ->
                        notifyData(WEILIANGYUANSU)
                                               );

        reVerData();

        refreshWeiyangView();

        img_today.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageSelectActivity.start(getAttachActivity(), new ImageSelectActivity.OnPhotoSelectListener() {

                    @Override
                    public void onSelected(List<String> data) {
                        toast("选择了" + data.toString());
                        imgPath = data.get(0);
                        img_today.setImageBitmap(BitmapUtils.getBitmapFromFileAddOpts(imgPath));
                    }

                    @Override
                    public void onCancel() {
                        toast("取消了");
                    }
                });
            }
        });

//        clearCurrentData();
        setDate();
        isInited = true;
    }

    private void clearCurrentData() {

        MMKVUtil.putString(DataOfKey.KEY_MMKV_CURRENT_WEIYANG, "");
        MMKVUtil.putString(DataOfKey.KEY_MMKV_CURRENT_SHENGLI, "");
        MMKVUtil.putString(DataOfKey.KEY_MMKV_CURRENT_WEILIANGYUANSU, "");
    }

    private void reVerData() {
        String weiyangData = weiyangAdapter.getCurrentJson();
        if (!weiyangData.equals("[]")) {
            if (getToday().equals(getMMKVDayInArray(weiyangData))) {
                setDatas(weiyangAdapterData, JsonUtil.fromJson(weiyangData, JsonArray.class), DataOfKey.KEY_WEIYANG);
            } else {
                clearCurrentData();
            }
        }

        String shenliData = shengliAdapter.getCurrentJson();
        if (!shenliData.equals("[]")) {
            if (getToday().equals(getMMKVDayInArray(shenliData))) {
                setDatas(shenliAdapterData, JsonUtil.fromJson(shenliData, JsonArray.class), DataOfKey.KEY_SHENGLI);
            } else {
                clearCurrentData();
            }
        }

        String weiliangyuansu = weiliangyuansuAdapter.getCurrentJson();
        if (!weiliangyuansu.equals("[]")) {
            if (getToday().equals(getMMKVDayInArray(weiliangyuansu))) {
                setDatas(weiliangyuansuAdapterData, JsonUtil.fromJson(weiliangyuansu, JsonArray.class), DataOfKey.KEY_WEILIANGYUANSU);
            } else {
                clearCurrentData();
            }
        }

        String todayWords = MMKVUtil.getString(DataOfKey.KEY_MMKV_CURRENT_TODAY_WORDS, "");
        if (!todayWords.equals("")) {
            if (getToday().equals(getMMKVDayInObject(todayWords))) {
                record_data_words.setText(getMMKVValueInObject(todayWords));
            } else {
                clearCurrentData();
            }
        }

        String todayImage = MMKVUtil.getString(DataOfKey.KEY_MMKV_CURRENT_TODAY_IMG, "");
        if (!todayImage.equals("")) {
            if (getToday().equals(getMMKVDayInObject(todayImage))) {
                img_today.setImageBitmap(BitmapUtils.getBitmapFromFileAddOpts(getMMKVValueInObject(todayImage)));
            } else {
                clearCurrentData();
            }
        }
    }

    private String getMMKVDayInArray(String json) {
        JsonArray object = JsonUtil.fromJson(json, JsonArray.class);
        JsonObject jsonElement = object.get(0).getAsJsonObject();
        return jsonElement.get(DataOfKey.KEY_MMKV_DAY).getAsString();
    }

    private String getMMKVDayInObject(String json) {
        JsonObject object = JsonUtil.fromJson(json, JsonObject.class);
        return object.get(DataOfKey.KEY_MMKV_DAY).getAsString();
    }

    private String getMMKVValueInObject(String json) {
        JsonObject object = JsonUtil.fromJson(json, JsonObject.class);
        return object.get(DataOfKey.KEY_MMKV_VALUE).getAsString();
    }

    private void setDatas(List<ItemEdit> adapter, JsonArray object, String type) {
        // 有缓存时取缓存数据
        adapter.clear();
        for (int i = 0; i < object.size(); i++) {
            JsonObject asJsonObject = object.get(i).getAsJsonObject();
            adapter.add(new ItemEdit(asJsonObject.get(DataOfKey.KEY_MMKV_EVENT).getAsString(),
                    asJsonObject.get(DataOfKey.KEY_MMKV_TIME).getAsString(), type));

        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            LogUtil.i(TAG, "隐藏");
            if (System.currentTimeMillis() - lastRefreshTime > 3000) {
                saveData();
            }
        } else {
            LogUtil.i(TAG, "显示");
        }
    }

    /**
     * 更新数据
     */
    private void saveData() {
        if (!isInited)
            return;
        if (weiyangAdapter == null ||
            shengliAdapter == null ||
            weiliangyuansuAdapter == null) {
            LogUtil.i(TAG, "adapter is null");
            return;
        }
        remark = record_data_words.getText().toString().trim();
        day = DateUtil.formatDay(date);
        LogUtil.i(TAG, "保存数据 start");
        MMKVUtil.putString(DataOfKey.KEY_MMKV_CURRENT_WEIYANG, weiyangAdapter.getCurrentJson());
        MMKVUtil.putString(DataOfKey.KEY_MMKV_CURRENT_SHENGLI, shengliAdapter.getCurrentJson());
        MMKVUtil.putString(DataOfKey.KEY_MMKV_CURRENT_WEILIANGYUANSU, weiliangyuansuAdapter.getCurrentJson());
        MMKVUtil.putString(DataOfKey.KEY_MMKV_CURRENT_TODAY_IMG, JsonString(imgPath, day));
        MMKVUtil.putString(DataOfKey.KEY_MMKV_CURRENT_TODAY_WORDS, JsonString(remark, day));

        String jsonDay = JsonUtil.getJsonByMMKVKey(day);
        jsonDay = JsonUtil.insertKeyValue(jsonDay, DataOfKey.KEY_MMKV_WEIYANG, weiyangAdapter.getCurrentJson());
        jsonDay = JsonUtil.insertKeyValue(jsonDay, DataOfKey.KEY_MMKV_SHENGLI, shengliAdapter.getCurrentJson());
        jsonDay = JsonUtil.insertKeyValue(jsonDay, DataOfKey.KEY_MMKV_WEILIANGYUANSU, weiliangyuansuAdapter.getCurrentJson());
        jsonDay = JsonUtil.insertKeyValue(jsonDay, DataOfKey.KEY_MMKV_TODAY_WORDS, JsonString(remark, day));
        jsonDay = JsonUtil.insertKeyValue(jsonDay, DataOfKey.KEY_MMKV_TODAY_IMG, JsonString(imgPath, day));
        LogUtil.i(TAG, "json = " + jsonDay);
        MMKVUtil.putString(day, jsonDay);
        String currentJson = JsonUtil.getJsonArrayByMMKVKey(DataOfKey.KEY_MMKV_DAYS);
        JsonObject currentDay = new JsonObject();
        currentDay.addProperty(DataOfKey.KEY_DAY, day);
        // 若存在则更新  不存在则添加 插入数据
        if (currentJson.equals("[]")) {
            currentJson = JsonUtil.insertArrayElement(currentJson, currentDay);
        } else {
            JsonArray jsonArray = JsonUtil.fromJson(currentJson, JsonArray.class);
            int contains = -1;
            for (int i = 0; i < jsonArray.size(); i++) {
                JsonObject jsonObject1 = jsonArray.get(i).getAsJsonObject();
                if (jsonObject1.get(DataOfKey.KEY_MMKV_DAY_POSITION).getAsString().equals(day)) {
                    contains = i;
                }
            }
            if (contains != -1) {
                currentJson = JsonUtil.upDateArrayElement(currentJson, currentDay, contains);
            } else {
                currentJson = JsonUtil.insertArrayElement(currentJson, currentDay);
            }
        }

        LogUtil.i(TAG, "保存数据 end" + currentJson);
        lastRefreshTime = System.currentTimeMillis();
    }

    private String JsonString(String value,String day){
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty(DataOfKey.KEY_MMKV_DAY, day);
        jsonObject.addProperty(DataOfKey.KEY_MMKV_VALUE, value);
        return jsonObject.toString();
    }
    private void setDate() {
        weiyangAdapter.setDate(date);
        shengliAdapter.setDate(date);
        weiliangyuansuAdapter.setDate(date);
    }

    private void notifyData(int KEY) {
        switch (KEY) {
            case WEIYANGTAG:
                weiyangAdapterData.add(new ItemEdit("添加记录", "时间", DataOfKey.KEY_WEIYANG));
                weiyangAdapter.notifyItemInserted(weiyangAdapterData.size() - 1);
                weiyangAdapter.notifyItemRangeChanged(weiyangAdapterData.size() - 1, weiyangAdapterData.size());
                refreshWeiyangView();
                break;
            case SHENLI:
                shenliAdapterData.add(new ItemEdit("添加记录", "时间", DataOfKey.KEY_SHENGLI));
                shengliAdapter.notifyItemInserted(shenliAdapterData.size() - 1);
                shengliAdapter.notifyItemRangeChanged(shenliAdapterData.size() - 1, shenliAdapterData.size());
                break;
            case WEILIANGYUANSU:
                weiliangyuansuAdapterData.add(new ItemEdit("添加记录", "时间", DataOfKey.KEY_WEILIANGYUANSU));
                weiliangyuansuAdapter.notifyItemInserted(weiliangyuansuAdapterData.size() - 1);
                weiliangyuansuAdapter.notifyItemRangeChanged(weiliangyuansuAdapterData.size() - 1, weiliangyuansuAdapterData.size());
                break;
        }
    }

    /**
     * 解决喂养不自动适配bug
     * 64=item高度 45=footer高度 4=padding*2
     */
    private void refreshWeiyangView() {
        LinearLayoutCompat.LayoutParams layoutParams = (LinearLayoutCompat.LayoutParams) linear_weiyang.getLayoutParams();
        layoutParams.height = DensityUtils.dip2px(getActivity(), 64 * weiyangAdapter.getItemCount() + 45 + 4);
        linear_weiyang.setLayoutParams(layoutParams);

    }

    private String getToday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    @SingleClick
    @Override
    public void onClick(View view) {

    }

    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }

    /**
     * {@link SwitchButton.OnCheckedChangeListener}
     */

    @Override
    public void onCheckedChanged(SwitchButton button, boolean checked) {
        toast(checked);
    }
}